'use strict';

angular.module('app')
    .controller('menuUpdateController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster',
    function($scope, $rootScope, $state, $timeout, toaster) {
        $scope.record = {
        	parent_id:0,
        	id:$state.params.id
        };
       
        if($state.includes('**.menu.update')){
            $scope.loading = true;
            $scope.title="编辑菜单";
            $scope.reset = false;//修改不允许重置
            var id = $state.params.id;
            activate(id);
        }else if($state.includes('**.menu.create')){
            $scope.title="添加菜单";
            $scope.reset = true;//新增时可以重置
        }
		//重置表单
		$scope.resetFrom = function(){
		    $scope.record = {
	        	parent_id:0,
	        	id:$state.params.id
        	}
		}
        //初始化验证
        validate();
        $scope.submit= function(){
            var m = $scope.record;
            if($scope.record.id != null){//id非空代表着是修改
            	if(m){
                    $scope.isDisabled = true;//提交disabled
                    $.ajax({
        				type: 'POST',
        	            dataType: 'json',
        				contentType:'application/json;charset=UTF-8',
        				url : '/menu/sysmenu/update',
        				data: angular.toJson($scope.record)
        			}).then(function(result){
        				if(result.httpCode ==200){//成功
	                        toaster.clear('*');
	                        toaster.pop('success', '', "保存成功");
	                        $timeout(function(){
	                            $state.go('main.sys.menu.list');
	                        },2000);
	                    }else{
	                        toaster.clear('*');
	                        toaster.pop('error', '', result.msg);
	                        $scope.isDisabled = false;
	                    }
        			});
                }
            }else{//id为空代表着是新增
            	if(m){
                    $scope.isDisabled = true;//提交disabled
                    $.ajax({
        				type: 'POST',
        	            dataType: 'json',
        				contentType:'application/json;charset=UTF-8',
        				url : '/menu/sysmenu/create',
        				data: angular.toJson($scope.record)
        			}).then(function(result){
        				if(result.httpCode ==200){//成功
	                        toaster.clear('*');
	                        toaster.pop('success', '', "保存成功");
	                        $timeout(function(){
	                            $state.go('main.sys.menu.list');
	                        },2000);
	                    }else{
	                        toaster.clear('*');
	                        toaster.pop('error', '', result.msg);
	                        $scope.isDisabled = false;
	                    }
        			});
                }
            }
        }

        var handleFileSelect=function(evt) {
            var file=evt.currentTarget.files[0];
            if(!/image\/\w+/.test(file.type)){
                return false;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                $scope.$apply(function($scope){
                    $scope.myImage=evt.target.result;
                });
            };
            reader.readAsDataURL(file);
        };
        angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);


        // 初始化页面
        function activate(id) {
	        $scope.loading = true;
        	$.ajax({
        		type: 'PUT',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : '/menu/sysmenu/detail',
				data: angular.toJson({'id': id})
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
					$scope.record = result.data;
					$scope.record.id = id;//给id值，因为后台需要根据是否有id值来操作：新增（无id）或者修改（有id）
					$scope.record.parent_id = $scope.record.parent_id+'';//解决修改页面无法回显的问题
					$scope.record.menu_type = $scope.record.menu_type+'';
					$scope.record.expand_ = $scope.record.expand_+'';
					console.log(result);
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
        }
        
        //查询父菜单编码
        $scope.loadParentIdList = function () {
		$scope.bparam = {};
		$scope.bparam.nopage = '1';
		$.ajax({
			type: 'POST',
            dataType: 'json',
			contentType:'application/json;charset=UTF-8',
			url : '/menu/parentid/list',
			data: angular.toJson($scope.bparam)
		}).then(function(result) {
			if (result.httpCode == 200) {
				$scope.sysMenu = result.data;
//				console.log(result);
				$scope.$apply();
			} 
			
		});
	 }
	$scope.loadParentIdList();
        
        //表单验证
        function validate(userId){
            jQuery('form').validate({
                rules: {
                	id_: {
                		required: true,
                		digits: true
                	},
                	expand_: {
                        required: true,
                    },
                    role_id: {
                        required: true,
                        digits: true
                    },
                    sort_no: {
                        required: true,
                        digits: true
                    },
                    parent_id: {
                        required: true
                    }
                },
                messages: {
                	id_: {
                		required: '请输入菜单编码',
                		digits: '请输入正整数'
                	},
                	expand_: {
                        required: '请选择状态',
                    },
                    role_id: {
                    	required: '请输入角色编码',
                        digits: '请输入正整数'
                    },
                    sort_no: {
                        required: '请填写排序',
                        digits: '请输入正整数'
                    },
                    parent_id: {
                        required: '请选择父菜单'
                    }
                },
                submitHandler: function() {
                    $scope.submit();
                }
            });
        }

    }]);